#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import os

def main():

	a  = "中国"
	au = u"中国"
	a_gb = au.encode("gbk")

	# 这里因为unicode会把每个元素都当成是一个unicode obj，所以len(au)结果是2
	# len(a)为6 因为标记字符集为utf-8，编码算出来是3个字节
	print len(a),len(au),len(a_gb)

	# utf-8 to unicode
	a_2_unicode1 = unicode(a, "utf-8")
	a_2_unicode2 = a.decode("utf-8")

	# a的unicode
	print a_2_unicode1, a_2_unicode2
	# a的gbk编码
	print a_gb

	my_code = "gbk"
	my_src  = u"我是来测试的一个字符串" + os.linesep
	file_path = "unicode_test"

	my_obj = unicode_read_write()
	my_obj.write(file_path, my_src, my_code)
	my_obj.read(file_path, my_code)

class unicode_read_write(object):

	def read(self, filepath, code):
		try:
			fobj = open(filepath, "r")
		except IOError:
			print "Cannot open file " + filepath
			sys.exit(-1)

		file_content = fobj.read()
		print file_content
		print file_content.decode(code)
		fobj.close()

	def write(self, filepath, src, code):
		try:
			fobj = open(filepath, "w")
		except IOError:
			print "Cannot open file " + filepath + " for writen"
			sys.exit(-1)
		file_content = src.encode(code)
		fobj.write(file_content)
		fobj.close()

if __name__ == "__main__":
	main()
